<!--
* description: 试驾车订单明细
* author: wangmaolin
* createdDate: 2020-11-24
* logs:
-->
<template>
  <section class="testDriver">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="true"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      :before-close="handleClose"
      width="70%"
      @close="closePopups"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="filter-container filter-params">
        <h3 :style="styleObj">内部用车信息</h3>
        <el-row ref="vailComponentList1" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents1.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :custom-obj="comp.customObj"
            :options="comp.options"
            :o-fields="comp.oFields"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 24"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>
      <div class="filter-container filter-params">
        <h3 :style="styleObj">开票信息</h3>
        <el-row ref="vailComponentList2" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents2.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 24"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div class="filter-container filter-params">
        <h3 :style="styleObj">
          车辆信息
        </h3>
        <el-row ref="vailComponentList4" :gutter="26">
          <el-table
            ref="multipleTable"
            :data="orderList"
            border
            style="width: 100%"
            max-height="200"
          >
            <el-table-column type="index" label="序号" align="center" />
            <el-table-column prop="auditView" width="150" label="审核意见" align="center">
              <template slot-scope="scope">
                <common-input
                  :ref="'opinion_'+ scope.$index"
                  :is-show-label="false"
                  :code="scope.row.auditView"
                  :span="24"
                  is-input
                  :com-type="scope.$index.toString()"
                  code-field="auditView"
                  :label-width="0"
                  :clearable="false"
                  :is-col-comp="true"
                  :cur-table-row="scope.row"
                  :readonly="readonly"
                  @changeCode="changeCode"
                />
              </template>
            </el-table-column>
            <el-table-column prop="carSeriesCn" label="车系" align="center" />
            <el-table-column prop="carConfigCn" label="基础车型" align="center" />
            <el-table-column prop="optionalPagName" label="选装包" align="center" />
            <el-table-column prop="carColorName" label="车身颜色" align="center" />
            <el-table-column prop="carIncolorName" label="内饰颜色" align="center" />
            <el-table-column prop="price" width="95" label="价格" align="center">
              <template slot-scope="scope">
                <common-input
                  :ref="'trueprice_'+ scope.$index"
                  :is-show-label="false"
                  :code="scope.row.price"
                  :span="24"
                  is-input
                  :com-type="scope.$index.toString()"
                  code-field="price"
                  :label-width="0"
                  :clearable="false"
                  :is-col-comp="true"
                  :cur-table-row="scope.row"
                  :readonly="readonly"
                  :is-require="true"
                  :validrule="{
                    // 保留一到两位小数
                    isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                    resectMessage: {
                      isformat: '请输入正确的价格，价格最多保留两位小数!'
                    }
                  }"
                  @changeCode="changeCode"
                />
              </template>
            </el-table-column>
            <el-table-column prop="dlrShortName" label="体验中心" align="center" />
            <el-table-column prop="orderNum" label="数量" align="center" />
          </el-table>
        </el-row>

      </div>
      <div v-show="isShowBtns" slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :disabled="comp.disabled"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>

import { formMixins } from '@/components/mixins/formMixins'
import commonInput from '../../../../components/org/commonInput'
import api from '@/api/testDriver'
export default {
  name: 'TDOrderApprovalEdit',
  components: {
    commonInput,
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题
  },
  // 组件混入对象
  mixins: [formMixins],
  data() {
    return {
      isShowBtns: true,
      // 验证状态
      valid: true,
      // 是否可以编辑
      readonly: false,
      // h3标题行内样式
      styleObj: { borderLeft: null },
      // 订单列表
      orderList: [],
      //
      genCodeFiled: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
      // 保存API配置对象
      apiConfig: this.dynamicApiConfig,
      // 动态组件-按钮
      tableButtons:
          [
            {
              isShow: true,
              text: '通过',
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              clickEvent: () => {
                this.$utils.validataMoth(this,
                  'validpopup',
                  undefined, 'multipleTable',
                  undefined, function(refs) {
                    const vpage = {}
                    for (const [key, item] of Object.entries(refs)) {
                      key.includes('trueprice') ? vpage[key] = [item] : ''
                    }
                    return vpage
                  }
                )
                if (this.valid) {
                  this.$requestAPI({
                    apiUrl: api.orderApprovalAccess.APIUrl,
                    variables: {
                      ...this.formField,
                      insaleOrderId: this.dynamicEditRowData.insaleOrderId,
                      controlId: this.dynamicEditRowData.controlId,
                      infoList: this.orderList
                    }
                  }).then(res => {
                    if (res.result === '1') {
                      res.msg ? this.$message(res.msg) : this.$message('审核成功!')
                      this.$emit('update:popupsVisible', false)
                      this.$parent.$refs['multipleTable'].queryTable()
                    } else {
                      res.msg ? this.$message(res.msg) : this.$message('审核失败!')
                      this.flushData()
                    }
                  }).catch(err => {
                    err.message ? this.$message(err.message) : this.$message(err.response.data.msg)
                  })
                }
              },
              disabled: false
            }, // '保存'
            {
              isShow: true,
              compKey: 'btnKey2',
              text: '驳回',
              type: '',
              size: 'small',
              clickEvent: () => {
                console.log(this.orderList)
                var reasonnotnull = this.orderList.every(item => {
                  if (item.auditView !== null) {
                    console.log(item.auditView.trim())
                    if (item.auditView.trim().length > 0) {
                      return true
                    } else {
                      return false
                    }
                  } else {
                    return false
                  }
                })
                if (!reasonnotnull) { this.$message('驳回请填写审核意见'); return }
                const { controlId, insaleOrderId } = this.dynamicEditRowData
                this.$utils.validataMoth(this,
                  'validpopup',
                  undefined, 'multipleTable',
                  undefined, function(refs) {
                    const vpage = {}
                    for (const [key, item] of Object.entries(refs)) {
                      key.includes('trueprice') ? vpage[key] = [item] : ''
                    }
                    return vpage
                  }
                )
                if (this.valid) {
                  this.$requestAPI({
                    apiUrl: api.orderApprovalReject.APIUrl,
                    variables: {
                      controlId,
                      insaleOrderId,
                      remark: this.formField.remark,
                      infoList: this.orderList
                    }
                  }).then(res => {
                    if (res.result === '1') {
                      res.msg ? this.$message(res.msg) : this.$message('驳回成功!')
                      this.$parent.$refs['multipleTable'].queryTable()
                      this.$emit('update:popupsVisible', false)
                    } else {
                      res.msg ? this.$message(res.msg) : this.$message('驳回失败!')
                    }
                  }).catch(err => {
                    err.message ? this.$message(err.message) : this.$message(err.response.data.msg)
                  })
                }
              },
              disabled: false
            } // 重置
          ],
      // 动态组件-查询条件
      tableComponents: [],
      tableComponents1:
          [
            {
              compKey: 'compKey2',
              labelName: '试驾车单号：',
              codeField: 'insaleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey5',
              labelName: '交付城市：',
              codeField: 'deliveryCityName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true,
              isRequire: true,
              span: 8
              // component: () => import('@/components/org/commonSelect'),
              // oFields: 'cityName,cityName',
              // customObj: {
              //   api: { APIUrl: api.cityList.APIUrl },
              //   listQuery: { provinceId: '' },
              //   selectType: '1'
              // },
              // type: 'dropdownList',
              // disabled: true,
              // isMust: true,
              // isRequire: true,
              // span: 8
            },
            {
              compKey: 'compKey6',
              labelName: '交付门店：',
              codeField: 'deliveryDlrId',
              textField: 'deliveryDlrShortName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              oFields: 'deliveryDlrId,deliveryDlrShortName',
              customObj: {
                api: { APIUrl: api.QueryCenterByList.APIUrl },
                listQuery: { cityId: '' }
              },
              isMust: true,
              disabled: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '开票城市：',
              codeField: 'deliveryCityName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true,
              isRequire: true,
              span: 8
              // oFields: 'cityId,cityName',
              // component: () => import('@/components/org/commonSelect'),
              // type: 'dropdownList',
              // isMust: true,
              // disabled: true,
              // isRequire: true,
              // span: 8
            },
            {
              compKey: 'compKey8',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 16
            }
          ],
      tableComponents2:
          [
            {
              compKey: 'compKey9',
              labelName: '客户类型：',
              codeField: 'customerCode',
              component: () => import('@/components/org/commonSelect'),
              lookuptype: 'VE0248',
              isMust: true,
              disabled: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey10',
              labelName: '企业名称：',
              codeField: 'invoiceCustName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey11',
              labelName: '联系电话：',
              codeField: 'invoiceCustPhone',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey12',
              labelName: '证件类型：',
              codeField: 'certificatesCode',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              lookuptype: 'VE0240',
              disabled: true,
              isMust: true,
              isRequire: true,
              span: 8
            },
            {
              compKey: 'compKey13',
              labelName: '社会信用代码：',
              codeField: 'invoiceCustCredCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMust: true,
              isRequire: true,
              span: 8
            }

          ],

      // 表单数据（无需赋值，由混入对象赋值）
      formField: {},
      initFormField: null
    }
  },
  watch: {
    curPopupsVisible(val) {
      if (val) {
        this.popupsState === 'edit' ? this.orderList = this.dynamicEditRowData.carInfo : ''
        // 订单状态 为已申请的才能够编辑 审核通过
        const orderStatus = this.dynamicEditRowData.insaleOrderStatus
        if (orderStatus !== '已申请') {
          this.tableButtons.forEach(item => { this.isShowBtns = false })
          this.readonly = true
        } else {
          this.tableButtons.forEach(item => { this.isShowBtns = true })
          this.readonly = false
        }
      }
      val ? this.setColor() : ''
      this.$emit('update:popupsVisible', val)
    }

  },
  created() {
    this.tableComponents = [...this.tableComponents1, ...this.tableComponents2]
    this.genCodeFiled = this.genUtil(this.tableComponents)
    this.formField = this.genCodeFiled('codeField')
    // this.$set(this.formField, 'explorationName', '')
    // this.$set(this.formField, 'vehicleConfigName', '')
    // this.$set(this.formField, 'insideCarTypeName', '')
  },
  mounted() {
    this.$requestAPI({
      apiUrl: api.cityList.APIUrl,
      variables: { provinceId: '' }
    }).then(response => {
      if (response.result === '1') {
        const comp = this.tableComponents.filter(item => item.codeField === 'invoiceCityId')
        comp[0].options = response.rows
      }
    }).catch(err => {
      console.log(err)
    })
    this.setColor()
  },
  methods: {
    flushData() {
      console.log(this.dynamicEditRowData)
      const { insaleOrderId } = this.dynamicEditRowData
      this.$requestAPI({
        apiUrl: api.orderApprovalQueryCar.APIUrl,
        variables: { insaleOrderId }
      }).then(response => {
        if (response.result === '1') {
          this.orderList = response.rows
        }
      }).catch(err => {
        console.log(err)
      })
    },
    changeCode(code, text, codeField, comType) {
      const d = parseInt(comType)
      this.orderList[d][codeField] = code
    },
    handleClose() {
      this.$emit('update:popupsVisible', false)
    },
    setColor() {
      const nowSystemColor = this.$store.getters.nowTheme.backgroundColor
      this.styleObj.borderLeft = `5px solid ${nowSystemColor}`
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    closePopups() {
      this.formField = this.genCodeFiled('codeField')
    },
    reset() {
      this.formField = this.genCodeFiled('codeField')
    }
  }
}
</script>
<style scoped>

  h3 {
    padding-left: 10px;
    text-align: left;
    font-weight: 600;
  }
  h3 button.el-button {
    float: right;
    margin-right: 10px;
  }

  div.filter-container {
    margin-bottom: 35px;
  }
  >>> div.el-col.el-col-24 {
    padding: 0 0 !important;

  }

</style>
